package panda.android.notebook.view;

import java.util.ArrayList;
import java.util.List;

import panda.android.notebook.Utils.Utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.PathEffect;
import android.graphics.PorterDuff.Mode;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;


public class Tuya extends View {

	public interface WordInterface {
		public void sendWord(Word word);
	}

	int left, top, right, bottom;

	WordInterface wordInterface;

	private List<Path> paths;
	private Word word;
	private Path mPath;
	private boolean isShow = false;

	public boolean isShow() {
		return isShow;
	}

	public void setShow(boolean isShow) {
		this.isShow = isShow;
		setVisibility(isShow ? VISIBLE : GONE);
	}

	private Paint mPaint;// 真实的画笔
	private boolean isClean = false;

	private Context mContext;
	private int viewWidth, viewHeight;

	// 手指离开时间
	long starttime;
	boolean flag;

	public static int width, height;// 屏幕長寬

	private Canvas writeCanvas;
	private Bitmap writeBitmap;

	public Tuya(Context context, AttributeSet attr) {
		super(context, attr);
		csh(context);
	}

	public Tuya(Context context) {
		super(context);
		csh(context);
	}

	public Tuya(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		csh(context);
	}

	public void setWordInterface(WordInterface wordInterface) {
		this.wordInterface = wordInterface;
	}

	private void csh(Context context) {
		this.mContext = context;
		paths = new ArrayList<Path>();
		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);// 设置外边缘
		mPaint.setStrokeCap(Paint.Cap.SQUARE);// 形状
		mPaint.setColor(Color.RED);
		mPaint.setStrokeWidth(20);// 画笔宽度

		setShow(false);
	}

	public void initLayout(Activity activity) {
		Utils utils = new Utils();
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				utils.width(300), utils.width(300));

		left = utils.screenWidth - utils.width(300);
		top = utils.screenHeight - utils.height(400);
		params.setMargins(left, top, right, bottom);
		setLayoutParams(params);
	}

	public void setTextColor(int color) {
		mPaint.setColor(color);
	}

	@Override
	public void onDraw(Canvas canvas) {

		if (viewHeight == 0 && viewWidth == 0) {
			viewWidth = getWidth();
			viewHeight = getHeight();
			writeBitmap = Bitmap.createBitmap(viewWidth, viewHeight,
					Config.ARGB_8888);
			writeCanvas = new Canvas(writeBitmap);
			word = new Word();
		}
		if (isClean) {
			// 清空
			word.savePaths();
			wordInterface.sendWord(word);
			paths.clear();
			writeCanvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
			isClean = false;
			// invalidate();
			refreshDrawableState();
			word = new Word();
		}

		// 绘制虚线
		drawLine(canvas);

		if (mPath != null) {
			canvas.drawPath(mPath, mPaint);
			writeCanvas.drawPath(mPath, mPaint);

		}

		for (Path path : paths) {
			canvas.drawPath(path, mPaint);
			writeCanvas.drawPath(path, mPaint);
		}

	}

	private void drawLine(Canvas canvas) {
		// TODO Auto-generated method stub

		if (listPaths.size() != 0) {
			for (Line line : listPaths) {
				canvas.drawPath(line.mPath, line.mPaint);
			}
			return;
		}
		{
			Paint paint = new Paint();
			paint.setAntiAlias(true);
			paint.setStyle(Paint.Style.STROKE);
			paint.setColor(Color.BLACK);
			paint.setStrokeWidth(3);

			PathEffect effects = new DashPathEffect(new float[] { 20, 20, 20,
					20 }, 1);
			paint.setPathEffect(effects);

			listPaths.add(new Line(getPath(0, 0, getWidth(), getHeight()),
					paint));
			listPaths.add(new Line(getPath(getWidth(), 0, 0, getHeight()),
					paint));

		}
		{
			Paint paint = new Paint();
			paint.setAntiAlias(true);
			paint.setStyle(Paint.Style.STROKE);
			paint.setColor(Color.BLACK);
			paint.setStrokeWidth(5);

			listPaths.add(new Line(getPath(0, 0, getWidth(), 0), paint));
			listPaths.add(new Line(getPath(getWidth(), 0, getWidth(),
					getHeight()), paint));
			listPaths.add(new Line(getPath(0, 0, 0, getHeight()), paint));
			listPaths.add(new Line(getPath(0, getHeight(), getWidth(),
					getHeight()), paint));
		}
		
		if (listPaths.size() != 0) {
			for (Line line : listPaths) {
				canvas.drawPath(line.mPath, line.mPaint);
			}
			return;
		}
	}

	private List<Line> listPaths = new ArrayList<Line>();

	private android.graphics.Path getPath(int startX, int startY, int endX,
			int endY) {
		android.graphics.Path path = new android.graphics.Path();
		path.reset();
		path.moveTo(startX, startY);
		path.lineTo(endX, endY);
		return path;
	}

	private float mX, mY;// 临时点坐标
	private static final float TOUCH_TOLERANCE = 4;

	/**
	 * 屏幕触摸开始
	 * 
	 * @param x
	 *            X坐标
	 * @param y
	 *            Y坐标
	 */
	public void touchStart(float x, float y) {
		mPath = new Path();
		mPath.moveTo(x, y);
		this.mX = x;
		this.mY = y;
		invalidate();
	}

	public void touchUp() {
		mPath.lineTo(mX, mY);
		paths.add(mPath);
		if (word != null)
			word.addPath(mPath);
		invalidate();
	}

	public void touchMove(float x, float y) {
		float dx = Math.abs(x - mX);
		float dy = Math.abs(y - mY);
		if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
			mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
			mX = x;
			mY = y;
		}
		invalidate();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			// 每次down下去重新new一个Path
			flag = false;
			touchStart(x, y);
			break;
		case MotionEvent.ACTION_MOVE:
			touchMove(x, y);
			break;
		case MotionEvent.ACTION_UP:
			touchUp();
			new SaveThread().start();
			break;
		}
		return true;
	}

	class SaveThread extends Thread {

		public SaveThread() {
			starttime = System.currentTimeMillis();
			flag = true;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			while (flag) {
				if (System.currentTimeMillis() - starttime > 500) {
					// 保存, 清空画布
					mPath = null;
					isClean = true;
					// 保存
					handler.sendEmptyMessage(0);
					flag = false;

				}
			}
		}
	}

	class Line {
		android.graphics.Path mPath;
		Paint mPaint;

		public Line(android.graphics.Path path, Paint paint) {
			mPaint = paint;
			mPath = path;
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				invalidate();
				break;
			default:
				break;
			}
		};
	};
}
